# 整理title
import datetime
import os
import re
import time


def insert_title(md_file):
    path_pre = '/Users/rustfisher/Desktop/ws/wiki-ws/mk-android-wiki-proj/mk-an-wiki/docs/'
    pattern = re.compile(r': (.*?).md', re.S)
    filepath_list = []  # 这么多的md文件
    with open(md_file) as md:
        for line in md.readlines():
            line = str(line)
            cur_urls = re.findall(pattern, line)
            if len(cur_urls) > 0:
                if cur_urls[0] == '/':
                    continue
                filepath_list.append(path_pre + cur_urls[0] + '.md')

    print('md文件总数', len(filepath_list))

    err_filepath_list = []
    for md_file in filepath_list:
        if not os.path.exists(md_file):
            err_filepath_list.append(md_file)
            continue
        has_lv1_title = False  # 是否有1级标题
        has_meta_title = False
        one_title = ''  # 1级标题
        with open(md_file) as md:
            for line in md.readlines():
                line = str(line)
                if line.startswith("# "):
                    has_lv1_title = True
                    one_title = str(line[2:]).strip()
                    continue
                if line.startswith("title: "):
                    has_meta_title = True
                    continue
        if has_lv1_title and not has_meta_title:
            print('需要meta_title', md_file)
            # copy_meta_title(md_file, one_title)
        elif not has_lv1_title and not has_meta_title:
            print('没有1级标题也没有meta_title,', md_file)


def copy_meta_title(md_file, title):
    """
    将1级标题复制为meta title
    :param md_file: 文件路径
    :param title: 标题
    :return: null
    """
    tmp_content = []
    with open(md_file, "r") as f:
        tmp_content = f.readlines()
    tmp_content.insert(1, 'title: ' + title + '\n')
    with open(md_file, "w") as f:
        f.writelines(tmp_content)


if __name__ == '__main__':
    print('开始整理 ----- ')
    insert_title('/Users/rustfisher/Desktop/ws/wiki-ws/mk-android-wiki-proj/mk-an-wiki/mkdocs.yml')
